package com.example.wenqujingdian.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.AudioDetailAdapter;
import com.example.wenqujingdian.api.ApiConfig;
import com.example.wenqujingdian.api.Contants;
import com.example.wenqujingdian.dialog.AlertDialog;
import com.example.wenqujingdian.model.AudioDetailBean;
import com.example.wenqujingdian.utils.QRCodeUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 具体分类
 */
public class AudioDetailActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.video_detail_recycler)
    RecyclerView recycler;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    private Unbinder bind;
    private static final String TAG = AudioDetailActivity.class.getCanonicalName();
    private List<AudioDetailBean.DataBean.ListBean> audioDetailList;

    private AudioDetailAdapter mAdapter;
    private boolean isRefresh;
    private int currentPage = 1;
    private int audioId;
    private String audioTitle;
    private String cover;
    private AlertDialog mDialog;

    private List<AudioDetailBean.DataBean.ListBean> audioPlays = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        bind = ButterKnife.bind(this);
        Bundle extras = getIntent().getExtras();
        audioId = extras.getInt("audioId");
        audioTitle = extras.getString("audioTitle");
        cover = extras.getString("imageUrl");
        title.setText(audioTitle);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initView();
        initData();
    }

    private void initView() {
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
    }

    private void initData() {
        audioDetailList = new ArrayList<>();
        setRefresh();
        getAudioDetailList(1);
        mAdapter = new AudioDetailAdapter(null);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        recycler.setAdapter(mAdapter);
    }

    private void getAudioDetailList(int page) {
        ViseHttp.GET(String.format(ApiConfig.AUDIO_CHILD_URL, audioId, page))
                .tag(TAG)
                .setHttpCache(true)
                //配置读取超时时间，单位秒
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<AudioDetailBean>() {
                    @Override
                    public void onSuccess(AudioDetailBean data) {
                        List<AudioDetailBean.DataBean> data1 = data.getData();
                        if (data1 == null) return;
                        AudioDetailBean.DataBean dataBean = data1.get(0);
                        if (isRefresh) {
                            audioDetailList = dataBean.getList();
                            mAdapter.replaceData(audioDetailList);
                        } else {
                            audioDetailList.addAll(dataBean.getList());
                            mAdapter.addData(dataBean.getList());
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.d("cordon", "onFail: " + errCode + "errMsg:" + errMsg);
                    }
                });
    }

    private void setRefresh() {
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                autoRefresh();
                refreshLayout.finishRefresh(1000);
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
                refreshLayout.finishLoadMore(1000);
            }
        });
    }

    private void loadMore() {
        isRefresh = false;
        currentPage++;
        getAudioDetailList(currentPage);
    }

    private void autoRefresh() {
        isRefresh = true;
        currentPage = 1;
        getAudioDetailList(currentPage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        ViseHttp.cancelTag(TAG);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        AudioDetailBean.DataBean.ListBean item = (AudioDetailBean.DataBean.ListBean) adapter.getItem(position);
        if (audioPlays.size() > 0){
            audioPlays.clear();
        }
        List<AudioDetailBean.DataBean.ListBean> data = mAdapter.getData();
        int index = data.indexOf(item);
        for (int i = index; i < data.size(); i++) {
            audioPlays.add(data.get(i));
        }
        Contants.playAudioList = audioPlays;
        startActivity(new Intent(this,AudioPlayActivity.class));
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        AudioDetailBean.DataBean.ListBean item = (AudioDetailBean.DataBean.ListBean) adapter.getItem(position);
        if (mDialog != null) {
            mDialog.dismiss();
        }
        Bitmap bitmap = getQRCode(item);
        mDialog = new AlertDialog.Builder(AudioDetailActivity.this, R.style.dialog)
                .setContentView(R.layout.dialog_layout)
                .setCancelable(false)
                .setText(R.id.name_tv, item.getAudioTitle())
                .setQrCode(R.id.qr_iv, bitmap)
                .setOnClickListener(R.id.delete_iv, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();
                    }
                })
                .show();
    }

    private Bitmap getQRCode(AudioDetailBean.DataBean.ListBean item) {
        String url = ApiConfig.API_URL + item.getAudioUrl() +
                "?favouriteId= " +item.getAudioId()+
                "&cover=" + cover +
                "&audioUrl=" + ApiConfig.API_URL + item.getAudioUrl() +
                "&audioName=" + item.getAudioTitle() +
                "&audioTitle=" + audioTitle;
        Log.e("mytest","----------"+url);
        return QRCodeUtil.createQRCodeBitmap(url, 280, 280);
    }
}
